const { json } = require("body-parser");
const express = require("express");
const mongoose = require("mongoose");
const Car = require("./model/car");
const User = require("./model/user");
const multer = require("multer");
var cookieParser = require("cookie-parser");

const storage = multer.diskStorage({
  // 保存路径
  destination: function (req, file, cb) {
    cb(null, "./public/uploads");
  },
  // 文件名
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, file.fieldname + "-" + uniqueSuffix + file.originalname);
  },
});
const upload = multer({ storage: storage });

const session = express();

// session.set("views", path.join(__dirname, "views")); // 设置模板文件的路径
// session.set("view engine", "ejs"); // ejs配置
session.use(express.json());
session.use("/", express.static("public"));
session.use(express.urlencoded({ extended: false }));
session.use(cookieParser());
// session.use(cookieParser());;
session.use("/api/cars", require("./route/cars"));
session.use("/api/cars", require("./route/cars"));
session.use("/api/cars/:id", require("./route/cars"));
session.use("/api/cars/:id", require("./route/cars"));
// session.use("/api/cars/:id", require("./route/cars"));

session.get("/api/users", (req, res) => {
  User.find()
    .sort({
      _id: -1,
    })
    .then((data) => {
      res.json(data);
    });
});

session.get("/api/users/:id", (req, res) => {
  User.findById(req.params.id).then((data) => {
    res.json(data);
  });
});
session.post("/api/users", async (req, res) => {
  const user = new User(req.body);
  await user.save();
  res.json({
    code: 1,
    msg: "添加成功",
  });
});
session.put("/api/users/:id", (req, res) => {
  User.findByIdAndUpdate(req.params.id, req.body).then((data) => {
    console.log(data);
    res.json({
      code: 1,
      msg: "修改成功",
    });
  });
});
session.delete("/api/users/:id", async (req, res) => {
  await User.findByIdAndRemove(req.params.id);
  res.json({
    code: 1,
    msg: "删除成功",
  });
});

session.post("/api/cars", (req, res) => {
  const car = new Car(req.body);
  car.save().then((data) => {
    console.log(data);
    res.json({
      code: 1,
      msg: "添加成功",
    });
  });
});

session.post("/api/upload", upload.single("file"), (req, res) => {
  // 文件上传就是把文件上传到服务器的目录中
  //  服务器返回一个可以访问的路径
  res.send({
    code: 1,
    info: "/uploads/" + req.file.filename,
  });
});

session.post("/api/login", (req, res) => {
  var postData = {
    phone: req.body.username,
    pwd: req.body.password,
  };
  console.log(postData);
  User.findOne(
    {
      phone: postData.phone,
      pwd: postData.pwd,
    },
    function (err, data) {
      if (err) throw err;
      if (data) {
        res.json({
          code: 1,
          msg: "登录成功",
        });
      } else {
        res.json({
          code: 0,
          msg: "登录失败",
        });
      }
    }
  );
});
//   const { phone, pwd } = req.body;
//   const p = req.body.phone;
//   if (phone && pwd) {
//     const user = User.find((item) => item.phone == p);
// if (user) {
//   if (user.pwd == pwd) {
//     res.cookie("user", user.phone); // 写cookie
//     res.json({
//       code: 1,
//       msg: "登录成功",
//     });
//   } else {
//     res.json({
//       code: 0,
//       msg: "登录密码错误",
//     });
//   }
// } else {
//   res.json({
//     code: 0,
//     msg: "用户信息不存在",
//   });
// }
// } else {
//   res.json({
//     code: 0,
//     msg: "请输入登录信息",
//   });
// }
// });
mongoose
  .connect("mongodb://localhost:27017/db-2101", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log("连接成功");
  });

session.listen(3000, () => {
  console.log("服务器运行成功");
});
module.exports = session;
